package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */

    @GetMapping("/page")
    public R<Page<Category>> page(Integer page,Integer pageSize){
        //1. 创建分页对象

        Page<Category> pageInfo = new Page<>(page, pageSize);

        //2. 创建LambdaQuery。。。。对象
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        //3.    添加分页查询条件 按sort由大到小排序
        queryWrapper.orderByDesc(Category::getSort);
        //4. 执行分页查询
        categoryService.page(pageInfo,queryWrapper); //结果封装到pageInfo对象中
        //5.返回pageInfo
        return R.success(pageInfo);


    }

    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("新增分类");
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    @PutMapping
    public  R<String> update(@RequestBody Category category){
        log.info("修改菜品分类....");
        categoryService.updateById(category);
        return R.success("修改成功");

    }

    @DeleteMapping
    public R<String> delete(long id){
        log.info("删除分类");

        categoryService.delete(id);
        return R.success("删除成功");
    }

    /**
     * 一级路径是category，二级路径是list，请求方式Get
     * 根据分类进行查询，查询结果按照sort升序排序，如果sort相同，按照修改时间排序
     * 要根据type=1 （菜品） type=2 （套餐）查询
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //1. 获取查询对象
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //2. 添加条件
        queryWrapper.orderByAsc(Category::getSort);
        queryWrapper.orderByDesc(Category::getUpdateTime);

        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //3. 调用方法
        List<Category> categoryList = categoryService.list(queryWrapper);
        return R.success(categoryList);
    }
}
